<?php

namespace App\Http\Middleware;

use App\Services\Admin\AuthService;
use App\Traits\ApiResponseTrait;
use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * 权限控制中间件
 */
class PermissionMiddleware
{
    use ApiResponseTrait;

    protected $authService;

    public function __construct(AuthService $authService)
    {
        $this->authService = $authService;
    }

    /**
     * 处理权限验证
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $user = $request->user();
        if (!$user) {
            return $this->unauthorized();
        }

        $route = $request->route();
        $action = $route[1]['uses'];
        [$controller, $method] = explode('@', $action);

        if (!$this->checkPermission($user, $controller, $method)) {
            return $this->forbidden();
        }

        return $next($request);
    }

    /**
     * @desc checkPermission
     * @param $user
     * @param string $controller
     * @param string $method
     * @return bool
     */
    protected function checkPermission($user, string $controller, string $method): bool
    {
        $userPermissions = $this->getUserPermissions($user->id);
        // 从完整的控制器路径中提取控制器名称
        $controllerName = class_basename($controller);
        $controllerName = lcfirst(str_replace('Controller', '', $controllerName));
        $permission = strtolower($controllerName) . '.' . strtolower($method);
        return in_array($permission, $userPermissions);
    }

    /**
     * 获取用户权限列表
     *
     * @param int $userId
     * @return array
     */
    protected function getUserPermissions(int $userId): array
    {
        return $this->authService->getUserPermissions($userId);
    }

    /**
     * 返回未授权响应
     *
     * @return JsonResponse
     */
    protected function unauthorized(): JsonResponse
    {
        return $this->error('未授权', 401);
    }

    /**
     * 返回无权限响应
     *
     * @return JsonResponse
     */
    protected function forbidden(): JsonResponse
    {
        return $this->error('无权限', 403);
    }
}
